<template>
  <div style="margin-top: 16px">
    <el-form :model="sendTaskForm" label-width="100px" size="small" >
      <el-form-item label="任务类型" prop="type" :rules="{ required: true, trigger: ['blur', 'change'] }">
        <el-select v-model="sendTaskForm.type" @change="changeType">
          <el-option v-for="item in typeList" :key="item.key" :label="item.name" :value="item.key" />
        </el-select>
      </el-form-item>
      <template v-if="sendTaskForm.type === 'mail'">
        <mail-task-panel id="id"></mail-task-panel>
      </template>
      <template v-else-if="sendTaskForm.type === 'mule'">
        <mule-task-panel id="id"></mule-task-panel>
      </template>
    </el-form>
  </div>
</template>

<script>
import MailTaskPanel from "./serviceTask/mailTaskPanel";
import MuleTaskPanel from "./serviceTask/muleTaskPanel";

export default {
  name: "SendTaskPanel",
  components: {MuleTaskPanel, MailTaskPanel},
  props: {
    id: {
      type: String,
      required: true
    },
  },
  data() {
    return {
      typeList: [
        {key: "mail", name: "邮件任务"},
        {key: "mule", name: "Mule任务"},
        // { key: "camel", name: "Camel任务"},
      ],
      sendTaskForm: {
        type: 'mail',
      },
    };
  },
  watch: {
    id: {
      immediate: true,
      handler() {
        this.$nextTick(() => this.getBindMessage());
      }
    }
  },
  methods: {
    resetTaskForm() {
      const {sendTaskForm} = this;
      for (let key in sendTaskForm) {
        let value = this.modelerStore.element?.businessObject[key] || sendTaskForm[key];
        this.$set(sendTaskForm, key, value);
      }
      this.deleteElementFormExtensions();
    },

    // 选择类型
    changeType(value) {
      this.sendTaskForm.type = value;
      if (this.sendTaskForm.type !== 'normal') {
        this.updateCustomElement('type', value);
      }
      this.deleteElementFieldExtensions();
    },

    updateCustomElement(key, value) {
      const taskAttr = Object.create(null);
      taskAttr[key] = value;
      this.modelerStore.modeling.updateProperties(this.modelerStore.element, taskAttr);
    },

    // 新建节点时,默认是用户节点,会添加表单相关扩展属性,当前任务直接删除掉
    deleteElementFormExtensions() {
      const element = this.modelerStore.element;
      if (element.businessObject?.extensionElements?.values) {
        element.businessObject.extensionElements.values =
          element.businessObject.extensionElements.values.filter(ex => ex.$type !== 'flowable:FormItems');
      }
    },

    // 切换服务类型时,删除之前配置的Field属性
    deleteElementFieldExtensions() {
      const element = this.modelerStore.element;
      if (element.businessObject?.extensionElements?.values) {
        element.businessObject.extensionElements.values =
          element.businessObject.extensionElements.values.filter(ex => ex.$type !== 'flowable:Field');
      }
    }
  },
};
</script>
